package com.atguigu.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author lwm1435@163.com
 * @date 2022-01-24 12:02
 * @description
 */
@Slf4j
@RequestMapping("/admin/core/dict")
@Api(tags = "数据字典管理")
@RestController
public class AdminDictController {
    @Resource
    private DictService dictService;


    @PostMapping("/import")
    public R importBatch(@ApiParam(value = "Excel数据字典文件",required = true)
                             @RequestParam MultipartFile file){
        try {
            dictService.importData(file.getInputStream());
            return R.ok().message("数据导入成功");
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("Excel数据的导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        // Swagger和EasyExcel有兼容问题，在使用Swagger对该方法进行测试时可能会产生问题
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            //设置文件名 防止中文乱码
            fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
            //以附件形式下载
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''"
                    + fileName + ".xlsx");
            //写入excel文件
            EasyExcel.write(response.getOutputStream(), ExcelDictDto.class)
                    .sheet("数据字典").doWrite(dictService.listDictData());
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR,e);
        }
    }

    //前端树形结构列表展示，
    // 后端数据 1.直接嵌套封装所有分类数据
    //        2 根据父id获取所有子节点，并添加一个字段(是否还包含子节点列表)
    @ApiOperation("根据父id获取子节点数据列表")
    @GetMapping("/listByParentId/{parentId}")
    public R listByParentId(@ApiParam(value = "父节点id")
                                @PathVariable Long parentId){
        List<Dict> dictList = dictService.listByParentId(parentId);
        return R.ok().data("list",dictList);
    }
}
